package com.fastjpa.service.impl;

import com.efeichong.dynamic.DS;
import com.efeichong.dynamic.DynamicDataSourceContextHolder;
import com.fastjpa.dao.ClazzDao;
import com.fastjpa.entity.Clazz;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lxk
 * @date 2022/9/1
 * @description
 */
@Component
@RequiredArgsConstructor
public class Test {
    private final ClazzDao clazzDao;

    /**
     * 因为session会跟事务绑定,DynamicDataSourceContextHolder手动切换无效,只能通过注解形式
     */
    @DS("master")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveMaster(){
        Clazz clazz = new Clazz();
        clazz.setName("master");
        clazzDao.save(clazz);
        throw new RuntimeException("ggg");
    }

    @DS("slave1")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveSlave1(){
        Clazz clazz = new Clazz();
        clazz.setName("slave1");
        clazzDao.save(clazz);
    }

    @DS("slave2")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveSlave2(){
        Clazz clazz = new Clazz();
        clazz.setName("slave2");
        clazzDao.save(clazz);
        throw new RuntimeException("ggg");
    }

    @DS("master")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public List<Clazz> getMaster() {
        return clazzDao.selectAll();
    }

    @DS("slave1")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public List<Clazz> getSlave1() {
        return clazzDao.selectAll();
    }

    @DS("slave2")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public List<Clazz> getSlave2() {
        return clazzDao.selectAll();
    }
}
